//
//  BaseModel.m
//  BaseProject
//
//  Created by Macx on 2018/2/24.
//  Copyright © 2018年 Gavin. All rights reserved.
//

#import "BaseModel.h"
#import "MainRequestAPI.h"
#import "UploadFileAPI.h"
#import "ResultModel.h"
#import "OtherRequestAPI.h"
#import "RHNavigationController.h"
#import "RHLoginViewController.h"
#import "RHTools.h"

//#import "EOWindowTipManage.h"
//#import "EduOnlineManage.h"
//#import "UserModel.h"

@implementation BaseModel

//返回一个 Dict，将 Model 属性名对映射到 JSON 的 Key。
/*+ (NSDictionary *)modelCustomPropertyMapper {
 return @{@"name" : @"n",
 @"page" : @"p",
 @"desc" : @"ext.desc",
 @"bookID" : @[@"id",@"ID",@"book_id"]};
 }*/

// 返回容器类中的所需要存放的数据类型 (以 Class 或 Class Name 的形式)。
/*+ (NSDictionary *)modelContainerPropertyGenericClass {
 return @{@"shadows" : [Shadow class],
 @"borders" : Border.class,
 @"attachments" : @"Attachment" };
 }*/


+ (NSDictionary *)modelContainerPropertyGenericClass {
    return @{@"results" : [self class]};
}

//2023.08.01新增
+ (void)startWithCompletionAPIKey:(NSString *)apiKey
                         header:(NSDictionary*)header
                         argument:(NSDictionary *)arguments
                   requestSuccess:(SuccessBlock)success
                      requestFail:(FailBlock)fail
{
    MainRequestAPI *request = [[MainRequestAPI alloc] initWithAPIKey:apiKey
                                                              header:header
                                                            argument:arguments
                                                       requestMethod:RequestMethodPOST];
    
    [self startWithRequest:request requestSuccess:success requestFail:fail];
}


+ (void)startWithCompletionAPIKey:(NSString *)apiKey
                         argument:(NSDictionary *)arguments
                   requestSuccess:(SuccessBlock)success
                      requestFail:(FailBlock)fail{

    MainRequestAPI *request = [[MainRequestAPI alloc] initWithAPIKey:apiKey
                                                              header:nil
                                                            argument:arguments
                                                       requestMethod:RequestMethodPOST];
    
    [self startWithRequest:request requestSuccess:success requestFail:fail];
}

+ (void)startGetWithCompletionAPIKey:(NSString *)apiKey
                            argument:(NSDictionary *)arguments
                      requestSuccess:(SuccessBlock)success
                         requestFail:(FailBlock)fail{
    
    MainRequestAPI *request = [[MainRequestAPI alloc] initWithAPIKey:apiKey
                                                              header:nil
                                                            argument:arguments
                                                       requestMethod:RequestMethodGET];
    
    [self startWithRequest:request requestSuccess:success requestFail:fail];
}

+ (void)startPutWithCompletionAPIKey:(NSString *)apiKey
                         argument:(NSDictionary *)arguments
                   requestSuccess:(SuccessBlock)success
                         requestFail:(FailBlock)fail{
    MainRequestAPI *request = [[MainRequestAPI alloc] initWithAPIKey:apiKey
                                                              header:nil
                                                            argument:arguments
                                                       requestMethod:RequestMethodPUT];
    
    [self startWithRequest:request requestSuccess:success requestFail:fail];
    
}


+ (void)startDeleteWithCompletionAPIKey:(NSString *)apiKey
                         argument:(NSDictionary *)arguments
                   requestSuccess:(SuccessBlock)success
                            requestFail:(FailBlock)fail{
    MainRequestAPI *request = [[MainRequestAPI alloc] initWithAPIKey:apiKey
                                                              header:nil
                                                            argument:arguments
                                                       requestMethod:RequestMethodDELETE];
    
    [self startWithRequest:request requestSuccess:success requestFail:fail];
}



+ (void)startWithBaseUrl:(NSString *)baseUrl
                 APIKey:(NSString *)apiKey
               argument:(NSDictionary *)arguments
          requestMethod:(RequestMethod)method
         requestSuccess:(SuccessBlock)success
            requestFail:(FailBlock)fail{
    OtherRequestAPI *request = [[OtherRequestAPI alloc] initWithBaseUrl:baseUrl
                                                                 APIKey:apiKey
                                                               argument:arguments
                                                          requestMethod:method];
    NSLog(@"---->request para:%@",arguments);
    [self startWithRequest:request requestSuccess:success requestFail:fail];
}



+ (void)startWithRequest:(BaseRequest *)request requestSuccess:(SuccessBlock)success requestFail:(FailBlock)fail{
    
    [request startWithCompletionBlockWithSuccess:^(__kindof BaseRequest * _Nonnull request) {
        ResultModel *resultModel;
        NSLog(@"request url === %@",request.requestUrl);
        NSLog(@"request.responseObject-------->:%@",request.responseObject);
        NSLog(@"request.responseString-------->:%@",request.responseString);
        [QMUITips hideAllTips];
//        [[ProgressHUDManage shareObject] hiddenLoadingAnimate];
        resultModel = [ResultModel yy_modelWithJSON:request.responseJSONObject];
        if (!resultModel) {
            NSLog(@"url === %@ -->数据格式错误！", request.requestUrl);
           
        }else{
            if (resultModel.code == 200) {
               
                if ([request.requestArgument isKindOfClass:[NSDictionary class] ]&&request.requestArgument[@"isReturn"]) {
                    if (success) {
                        success(request,resultModel);
                    }
                    return;
                }
                
                if([resultModel.data isKindOfClass:[NSDictionary class]]) {
                    resultModel.data = [[self class] yy_modelWithJSON:resultModel.data];
                }
                
                if ([resultModel.data isKindOfClass:[NSArray class]]) {
                    resultModel.data = [NSArray yy_modelArrayWithClass:[self class] json:resultModel.data];
                }
                
                if ([resultModel.rows isKindOfClass:[NSArray class]]) {
                    resultModel.data = [NSArray yy_modelArrayWithClass:[self class] json:resultModel.rows];
                }
                
               
//                NSLog(@"result === %@",request.responseJSONObject);
                
                
//                NSLog(@"msg ===== %@",resultModel.message);
                 
                if (success) {
                    success(request,resultModel);
                }
            }else if (resultModel.code == 401){
                [SVProgressHUD dismiss];
                [ProgressHUDManage hideTips];
                
                [UserDefaults setBool:NO forKey:kIsLogined];
                [UserDefaults setObject:@"" forKey:kToken];
                if([PrivateMange share].isShowLoginExpired == YES) return;
                
                //登录过期
                UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示".rh_localized message:@"登录过期,请重新登录!".rh_localized preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定".rh_localized style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    [PrivateMange share].isShowLoginExpired = NO;
                    RHNavigationController *nav = [[RHNavigationController alloc]initWithRootViewController:[[RHLoginViewController alloc]init]];
                    [UIApplication sharedApplication].keyWindow.rootViewController = nav;
                    
                }];
                [alertVC addAction:sure];
                
                [[RHTools getCurrentVC] presentViewController:alertVC animated:YES completion:nil];
                [PrivateMange share].isShowLoginExpired = YES;
                    
                    
              
                
            }else{
                [SVProgressHUD dismiss];
                [ProgressHUDManage hideTips];
                if ([resultModel.message length]>0) {
                    [QMUITips showError:resultModel.message];
                }
                NSLog(@"error ===== %@",resultModel.message);
                if (success) {
                    success(request,resultModel);
                }
            }
        }
        
    } failure:^(__kindof BaseRequest * _Nonnull request) {
        [QMUITips hideAllTips];
        [SVProgressHUD dismiss];
        [ProgressHUDManage hideTips];
        ReachabilityStatus status = [GLobalRealReachability currentReachabilityStatus];
        ResultModel *resultModel;
        if (status == RealStatusNotReachable) {
            resultModel = [[ResultModel alloc] init];
            resultModel.message = @"No connection.";
            resultModel.code = -200;
        } else {
            resultModel = [ResultModel yy_modelWithJSON:request.responseJSONObject];
            if (resultModel) {
                resultModel.code = -400;
            }else{
                resultModel = [[ResultModel alloc] init];
                resultModel.message = @"Server access failed, please try again later.";
                resultModel.code = -200;
            }
        }
        
        resultModel.data = nil;
        resultModel.sessionkey = @"";
        if (fail) {
            fail(request,resultModel);
        }
    }];
}



//上传单张图片
+ (void)startUploadWithCompletionAPIKey:(NSString *)apiKey
                                rgument:(NSDictionary *)arguments
                                  image:(UIImage *)image
                              imageName:(NSString *)imageName
                         requestSuccess:(SuccessBlock)success
                            requestFail:(FailBlock)fail{
    
    UploadFileAPI *request = [[UploadFileAPI alloc] initWithAPIKey:apiKey argument:arguments image:image imageName:(NSString *)imageName];
    [request startWithCompletionBlockWithSuccess:^(__kindof BaseRequest * _Nonnull request) {
        [QMUITips hideAllTips];
        ResultModel *resultModel = [ResultModel yy_modelWithJSON:request.responseJSONObject];
        NSLog(@"请求url === %@",request.requestUrl);
        NSLog(@"request.responseObject-------->:%@",request.responseObject);
        if (!resultModel) {
            NSLog(@"apiKey === %@ -->数据格式错误！",apiKey);
            if (success) {
                success(request,nil);
            }
        }else{
            if (resultModel.code == 200) {
                if ([resultModel.data isKindOfClass:[NSDictionary class]]) {
                    
                    resultModel.data = [[self class] yy_modelWithJSON:resultModel.data];
                }
                
                if ([resultModel.data isKindOfClass:[NSArray class]]) {
                    
                    resultModel.data = [NSArray yy_modelArrayWithClass:[self class] json:resultModel.data];
                }
                
//                NSLog(@"result === %@",request.responseJSONObject);
//                NSLog(@"msg ===== %@",resultModel.message);
                
                if (success) {
                    success(request,resultModel);
                }
            }else{
                if ([resultModel.message length]>0) {
                    [SVProgressHUD showErrorWithStatus:resultModel.message];
                }
                NSLog(@"error ===== %@",resultModel.message);

                if (success) {
                    success(request,nil);
                }
            }
        }
    } failure:^(__kindof BaseRequest * _Nonnull request) {
        [QMUITips hideAllTips];
        ReachabilityStatus status = [GLobalRealReachability currentReachabilityStatus];
        if (status == RealStatusNotReachable) {
            [SVProgressHUD showErrorWithStatus:@"The current network is not available. Please check the network settings"];
        } else {
            [SVProgressHUD showErrorWithStatus:@"Server access failed. Please try again later"];
        }
        ResultModel *resultModel = [[ResultModel alloc] init];
        resultModel.message = @"failed";
        resultModel.code = -200;
        resultModel.data = nil;
        resultModel.sessionkey = @"";
        if (fail) {
            fail(request,resultModel);
        }
    }];
}


//上传文件
+ (void)startUploaFiledWithCompletionAPIKey:(NSString *)apiKey
                                 rgument:(NSDictionary *)arguments
                                   filePath:(NSString *)filePath
                          requestSuccess:(SuccessBlock)success
                             requestFail:(FailBlock)fail{
    
    UploadFileAPI *request = [[UploadFileAPI alloc] initWithAPIKey:apiKey argument:arguments filePath:filePath];
    [request startWithCompletionBlockWithSuccess:^(__kindof BaseRequest * _Nonnull request) {
        [QMUITips hideAllTips];
        ResultModel *resultModel = [ResultModel yy_modelWithJSON:request.responseJSONObject];
        NSLog(@"请求url === %@",request.requestUrl);
        NSLog(@"request.responseObject-------->1111:%@",request.responseObject);
        if (!resultModel) {
            NSLog(@"apiKey === %@ -->数据格式错误！",apiKey);
            if (success) {
                success(request,nil);
            }
        }else{
            if (resultModel.code == 200) {
                if ([resultModel.data isKindOfClass:[NSDictionary class]]) {
                    
                    resultModel.data = [[self class] yy_modelWithJSON:resultModel.data];
                }
                
                if ([resultModel.data isKindOfClass:[NSArray class]]) {
                    
                    resultModel.data = [NSArray yy_modelArrayWithClass:[self class] json:resultModel.data];
                }
                
//                NSLog(@"result === %@",request.responseJSONObject);
//                NSLog(@"msg ===== %@",resultModel.message);
                
                if (success) {
                    success(request,resultModel);
                }
            }else{
                if ([resultModel.message length]>0) {
                    [SVProgressHUD showErrorWithStatus:resultModel.message];
                }
                NSLog(@"error ===== %@",resultModel.message);

                if (success) {
                    success(request,nil);
                }
            }
        }
    } failure:^(__kindof BaseRequest * _Nonnull request) {
        [QMUITips hideAllTips];
        ReachabilityStatus status = [GLobalRealReachability currentReachabilityStatus];
        if (status == RealStatusNotReachable) {
            [SVProgressHUD showErrorWithStatus:@"The current network is not available. Please check the network settings"];
        } else {
            [SVProgressHUD showErrorWithStatus:@"Server access failed. Please try again later"];
        }
        ResultModel *resultModel = [[ResultModel alloc] init];
        resultModel.message = @"failed";
        resultModel.code = -200;
        resultModel.data = nil;
        resultModel.sessionkey = @"";
        if (fail) {
            fail(request,resultModel);
        }
    }];
}
@end
